--[[
-- Author:      feilong
-- DateTime:    2020-10-10 17:19:33
-- Description: 节点间的消息处理
    
--]]


local skynet = require "skynet"
local cjson = require "cjson"

local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor()
	self.agents = {}
    self.sessions = {}

	self:register()	
end

--注册本服务里的消息
function MessageHandler:register()    
    g.Log():debug("i am manager register!")
    self.message_dispatch = g.MsgDis()
    self.message_dispatch:register('start', handler(self, self.start))
    self.message_dispatch:register("send_to_user", handler(self, self.sendToUser))
    
    self.message_dispatch:registerDefault(handler(self, self.defaultMsg))
end

function MessageHandler:showService()  
    --加载了的服务列表
    g.Message():callService(".launcher", "LIST")
    g.Log():debug("list--> ", list, skynet.self())
end


function MessageHandler:sendToUser(uid, msg_name, msg_data)
    -- body
    g.Log():debug("______send_to_user__", uid, msg_name)
    local session = self.sessions[uid]
    g.cluster_manager:sendGate(session, msg_name, msg_data)
end



---------------------------------------------------------
-- CMD
---------------------------------------------------------
function MessageHandler:start()
    print("manager start")
end


--转给agent
function MessageHandler:defaultMsg(uid, client_info, msg_name, msg_data)
    local agent = self.agents[uid]
    if not agent then 
        self.agents[uid] = 0
        agent = skynet.newservice("agent/agent_service")
        g.Message():sendService(agent, "start", client_info)
        self.agents[uid] = agent
        self.sessions[uid] = client_info.s
    elseif agent == 0 then 
        print('sending request too fast,service is not created completely yet')
        return        
    end
    local session = self.sessions[uid]
    if session == 0 then
        g.Log():error(uid,'intersected data when insteading')
        return
    end
    --假如不是同一个会话，则需要新会话覆盖旧会话
    local s = client_info.s
    print("___client_info", uid, client_info, msg_name, msg_data)
    if s ~= session then
        g.Log():debug('now instead uid', uid, session, s)
        self.sessions[uid] = 0
        if not g.Message():callService(agent, "instead", client_info) then
            --还回去
            self.sessions[uid] = session
            g.Log():error(uid, 'failed to instead', s)
            return
        end
        assert(self.sessions[uid] == 0, string.format('inconsistency state %d', uid))
        self.sessions[uid] = s
    end

    g.Message():sendService(agent, msg_name, msg_data)
end

return MessageHandler